package com.rabbitmq;

import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * 把数据发送到rabbitmq的exchange，
 */
public class SendToExchange {
    static Logger log = LoggerFactory.getLogger(SendToExchange.class);
    
    final static String TYPE = "topic";
    final static String CHARSET_UTF8 = "UTF-8";
    //MQ生产者exchange，把数据发给这个exchange
    final static String rabbitExchangeName = "ExchangeName";
    static boolean mqConnected = false;//mq当前处于连接状态
    
    static Channel channel=null;
    static{
        init();
    }
    public static void init(){
        log.info(" rabbit mq init begin...");
        try {
            //在mq连接中断后，发送程序判断已经断开，启动重连的时候会执行
            if(channel!=null){
                try {
                    channel.close();
                } catch (Exception e) {
                    log.error("关闭老channel 异常",e);
                }finally{
                    channel = null;
                }
            }
            Connection connection = RabbitMqConnectFactory.getConnection("connection");
            channel = connection.createChannel();
            /*
             *这里只定义exchange，因为每个业务模块都会从这里接入数据，所以不在这里定义队列
             *队列的定义在各个业务模块自己的消费端定义
             */
            channel.exchangeDeclare(rabbitExchangeName, TYPE, true, false, null);
            log.info(" rabbit mq init OK");
            mqConnected = true;
        } catch (Exception e) {
            log.error("rabbitmq初始化错误",e);
            mqConnected = false;
        }
    }
    /**
     * 往rabbitmq发数据
     * @param message
     */
    public static void sendToRabbitMq(String message,String routingKey){
        try {
            if(StringUtils.isEmpty(message)){
                log.debug("message is empty");
                return;
            }
            channel.basicPublish(rabbitExchangeName, routingKey, null, message.getBytes(CHARSET_UTF8));
        }catch(AlreadyClosedException ex){
            log.error("往rabbitmq发数据报错,可能连接已关闭,尝试重连,data:",message,ex);
            init();
        }catch (Exception e) {
            log.error("往rabbitmq发数据报错,data:",message,e);
        }
    }
}